<template>
  <el-row class="node_welcone_msg_box">
    <div class="switch_box">
      <el-switch
        v-model="usingWelcomeMsg"
        active-color="#13ce66"
        inactive-color="#ff6b6b"
        @change="useChange">
      </el-switch>
      <span class="switch_box_text">启用不同时段展示不同欢迎语</span>
    </div>
    <el-col v-show="usingWelcomeMsg" :span="7">
      <div class="prompit">
        温馨提示：</br>
        1.请点击右侧编辑图标进行编辑欢迎语</br>
        2.不同时段欢迎语最多添加6条</br>
        3.时间格式：时:分 或 *, 如 09:00
      </div>
      <div class="msg_list_box_head">
        <span class="head_title" @click="addOne()"><i class="el-icon-plus"></i>添加欢迎语</span>
      </div>
      <div v-for="(welcomeMsg, index) in welMsgUl" class="msg_list_box">
        <span class="title_border"></span>
        <span class="iconfont icon-beizhu todo_btn_edit" @click="editOne(index, welcomeMsg)"></span>
        <span class="todo_btn" @click="lessOne(index)" ><i class="el-icon-minus"></i></span>
        <div class="welcone_msg_box" v-html="welcomeMsg.content"></div>
        <div class="welcone_msg_time">展示时间：{{welcomeMsg.startTime}}——{{welcomeMsg.endTime}}</div>
      </div>
    </el-col>
    <el-col :span="14" class="welcone_msg_edit_box" v-show="welcomeMsgEditShow">
      <el-form :model="editorClone" ref="editorClone">
        <el-row class="msg_time_box" v-show="usingWelcomeMsg">
          <el-col :span="3" class="msg_time_box_title">展示时间:</el-col>
          <el-col :span="9" class="start_input">
            <el-form-item prop="startTime">
              <el-input v-model.trim="editorClone.startTime" placeholder="请输入开始时间"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item prop="endTime">
              <el-input v-model.trim="editorClone.endTime" placeholder="请输入结束时间"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div>展示内容：</div>
      <div id="welcomeMsgEditorMenu"></div>
      <div id="welcomeMsgEditorCon"></div>
      <div class="editor_btn_box" v-show="usingWelcomeMsg">
        <el-button type="primary" class="primary_btn save_welcome_msg" @click="saveWelcomeMsg">保存欢迎语</el-button>
        <el-button type="primary" class="primary_btn delete_btn" @click="cancelUpdate">取消编辑欢迎语</el-button>
      </div>
    </el-col>
  </el-row>
</template>
<script>
  import Editor from 'wangeditor'
  import * as uuid from 'uuid'
  import {uploadTo7moorEmailDomain} from '@utils/qiniuUtils'
  import { deepClone, filterXSS } from '@utils/m7Utils'
  export default {
    name: 'webchatWelcomeMsg',
    data () {
      return {
        editorClone: {content: '', startTime: '', endTime: ''},
        editIndex: 0,
        welcomeMsgEditShow: false,
        editor: {},
        editorType: '',
        usingWelcomeMsg: false,
        welMsgUl: [],
        welMsg: '',
        m7uploaders: []
      }
    },
    props: {
      usingMultiWelcomeMessage: {
        type: Boolean,
        default: false
      },
      welcomeMessage: {
        type: String,
        default: ''
      },
      welcomeRandom: {
        type: Number,
        default: 0
      },
      welcomeMessages: {
        type: Array,
        default: function () {
          return {
            isShow: false,
            alink: []
          }
        }
      }
    },
    methods: {
//      启用按钮发生变化
      useChange (data) {
        this.$emit('usingChange', data)
        if (data) {
          this.welcomeMsgEditShow = false
        } else {
          this.editorClone.content = this.welMsg
          this.editor.txt.html(filterXSS(this.editorClone.content))
          this.welcomeMsgEditShow = true
        }
      },
      initUploadImageFile () {
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          console.log('uploadProgress1')
        }
        let uploadComplete = function () {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          // self.editor.txt.append('<img src="' + sourceLink + '" alt="">')
          // 改为图片在光标出插入
          self.editor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
          self.editorClone.content = self.editor.txt.html()
          if (self.usingWelcomeMsg === false) {
            self.$emit('messageChg', self.editorClone.content)
          }
        }
        let error = function (up, err, errTip) {
          self.$message.error(errTip)
        }
        let key = function (up, file) {
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          let key = 'email/' + time + '/' + uuid.v1() + '/' + fileName
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp'}
          ]
        }
        this.m7uploaders.push(
          uploadTo7moorEmailDomain(this.sessionUserId, 'w-agent-node-img-icon', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
        )
      },
      editOne (index, data) {
        console.log(this.welMsgUl)
        this.welcomeMsgEditShow = true
//        this.$refs['editorClone'].resetFields()
        this.editIndex = index
        this.editorClone = deepClone(data)
        this.editor.txt.html(filterXSS(this.editorClone.content))
        this.editorType = 'update'
      },
      saveWelcomeMsg () {
        let that = this
        this.$refs['editorClone'].validate((valid) => {
          if (valid) {
            if (!this.transferForm(that.editorClone.startTime, that.editorClone.endTime)) {
              return
            }
            if (that.editorType === 'add') {
              that.welMsgUl.push(that.editorClone)
            } else {
              that.welMsgUl[this.editIndex] = that.editorClone
            }
            that.$emit('messageArrChg', that.welMsgUl)
            that.welcomeMsgEditShow = false
            that.editorClone = {content: '', startTime: '', endTime: ''}
          }
        })
      },
      cancelUpdate () {
//        this.$refs['editorClone'].resetFields()
        this.editorClone.content = ''
        this.editor.txt.html('')
        this.welcomeMsgEditShow = false
      },
      addOne () {
//        this.$refs['editorClone'].resetFields()
        if (this.welMsgUl.length >= 6) {
          this.$message.error('最多可添加6条')
          return
        }
        this.editorClone = {content: '', startTime: '', endTime: ''}
        this.editor.txt.html(filterXSS(this.editorClone.content))
        this.editorType = 'add'
        this.welcomeMsgEditShow = true
      },
      lessOne (index) {
        this.welMsgUl.splice(index, 1)
        this.$emit('messageArrChg', this.welMsgUl)
        this.welcomeMsgEditShow = false
      },
      transferForm (start, end) {
        let datePattern = new RegExp(/^([01][0-9]|[2][0-3]):[0-5][0-9]$/)
        if (start === '') {
          this.$message.error('开始时间必填')
          return false
        } else if (!datePattern.test(start) && start !== '*') {
          this.$message.error('请输入正确的开始时间！')
          return false
        }
        if (end === '') {
          this.$message.error('结束时间必填')
          return false
        } else if (!datePattern.test(end) && end !== '*') {
          this.$message.error('请输入正确的结束时间！')
          return false
        }
        return true
      },
      initBox () {
        if (this.usingWelcomeMsg === false) {
          this.welcomeMsgEditShow = true
        } else {
          this.welcomeMsgEditShow = false
        }
        if (this.editor.txt) {
          this.editor.txt.html(filterXSS(this.welcomeMessage))
        }
      }
    },
    watch: {
      welcomeRandom (cur) {
        this.initBox()
      },
      usingMultiWelcomeMessage (cur) {
        this.usingWelcomeMsg = cur
        if (cur === false) {
          this.welcomeMsgEditShow = true
        } else {
          this.welcomeMsgEditShow = false
        }
      },
      welcomeMessage (cur) {
        this.welMsg = cur
      },
      welcomeMessages (cur) {
        this.welMsgUl = cur
      }
    },
    computed: {
      sessionUserId () {
        return this.$store.state.session.user._id
      }
    },
    mounted () {
      this.editor = new Editor('#welcomeMsgEditorMenu', '#welcomeMsgEditorCon')
      this.editor.config.menus = [
        'head',  // 标题
        'bold',  // 粗体
        'fontSize',  // 字号
        'fontName',  // 字体
        'italic',  // 斜体
        'underline',  // 下划线
        'strikeThrough',  // 删除线
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'justify'  // 对齐方式
      ]
      this.editor.config.pasteTextHandle = filterXSS
      this.editor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
      let that = this
      let lang = window.langJson || {}
      let editLang = lang.wangeditor
      this.editor.config.lang = editLang
      this.editor.config.onchange = (html) => {
        // html 即变化之后的内容
        if (new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(that.editorClone.content)) {
          that.editorClone.content = that.subContent.content.replace(/<table border="0" width="100%" cellpadding="0" cellspacing="0">/g, '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">')
        }
        that.editorClone.content = that.editor.txt.html()
        if (that.usingWelcomeMsg === false) {
          this.$emit('messageChg', that.editorClone.content)
        }
      }
      this.editor.config.zIndex = 100
      this.editor.create()
      this.editor.txt.html(filterXSS(that.editorClone.content))
      let div = document.createElement('div')
      div.className = 'w-e-menu'
      div.style.cssText = 'z-index:101;'
      let span = document.createElement('i')
      span.className = 'w-e-icon-image'
      span.id = 'w-agent-node-img-icon'
      div.appendChild(span)
      document.getElementsByClassName('w-e-toolbar')[0].appendChild(div)
      this.initUploadImageFile()
      this.initBox()
    },
    beforeMount () {
      this.usingWelcomeMsg = this.usingMultiWelcomeMessage
      this.welMsgUl = this.welcomeMessages
      this.welMsg = this.welcomeMessage
      this.initBox()
    },
    beforeDestroy () {
      this.m7uploaders.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
    }
  }

</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .prompit
    color $c-prompt
    padding 6px 0 12px
  .switch_box
    margin-bottom 16px
    .switch_box_text
      margin-left 10px
  .msg_list_box_head
    background #f4f4f4
    height 50px
    line-height 50px
    padding-left 20px
    .head_title
      cursor pointer
  .el-icon-plus
    margin-right 10px
    color $c-main
  .msg_time_box
    margin 8px 0 10px 0
    .msg_time_box_title
      line-height 40px
  .msg_list_box
    position relative
    padding 8px 50px 8px 8px
    background #f4f4f4
    .todo_btn,.todo_btn_edit
      cursor pointer
      position absolute
      right 6px
      color $c-main
    .todo_btn_edit
      right 26px
    .welcone_msg_box
      width 100%
      word-break break-all
      color #737373
  .title_border
    position absolute
    height 1px
    background #ccc
    width 96%
    margin 0 auto
    display inline-block
    top 0
  .welcone_msg_col
    position relative
    .icon-beizhu
      position absolute
      cursor pointer
      right 4px
      top 0
      color $c-main
  .start_input
    position relative
    margin-right 24px
    &:before
      content: ''
      border-top 2px solid $c-border2
      width 16px
      position absolute
      top 15px
      right -20px
  .welcone_msg_edit_box
    margin-left 30px
    padding-top 6px
  .delete_btn
    background-color #ff6b6b
    border-color #ff6b6b
  .save_welcome_msg
    margin-top 10px
  .w-e-toolbar
    background-color #f1f1f1
    border 1px solid #ccc
  #welcomeMsgEditorCon
    border 1px solid #ccc
    border-top none
    height 220px
</style>
